package xyz.xtt.exchange.mq;

import static xyz.xtt.common.asset.AssertUtils.isNull;

import java.nio.charset.StandardCharsets;
import java.util.Objects;

import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import xyz.xtt.asset.client.AssetClient;
import xyz.xtt.exchange.constants.ErrorMessage;
import xyz.xtt.exchange.service.IInnerService;
import xyz.xtt.exchange.service.ITblAssetAuditService;
import xyz.xtt.pay.api.dto.BusinessOrderStatusChangeMsg;
import xyz.xtt.pay.client.response.BusinessOrderResponse;

/**
 * 个人铸造V2业务订单支付取消修改审核记录状态
 * 
 * @author dale
 * @date 2025/3/17
 **/
@RefreshScope
@Slf4j
@Component
@RocketMQMessageListener(topic = "${rocketmq.business.order.status.change.topic:nft_business_order_status_change}", selectorExpression = "PERSONAL_MINT_V2:PAY_CANCEL", consumerGroup = "${rocketmq.consumer.group.exchange.mintOrderPayStatusChange:nft_exchange_mintOrderPayStatusChange}")
public class PersonalMintBusinessOrderPayStatusChangeConsumer implements RocketMQListener<MessageExt> {
	@Autowired
	private AssetClient assetClient;
	@Autowired
	private ITblAssetAuditService tblAssetAuditService;
	@Autowired
	private IInnerService iInnerService;

	@Override
	public void onMessage(MessageExt msg) {
		String msgId = msg.getMsgId();
		byte[] body = msg.getBody();
		String message = new String(body, StandardCharsets.UTF_8);
		log.info("PersonalMintBusinessOrderPayStatusChangeConsumer msgId:{} message: {}", msgId, message);
		if (StringUtils.isEmpty(message)) {
			return;
		}
		if (!JSONUtil.isTypeJSON(message)) {
			log.warn("PersonalMintBusinessOrderPayStatusChangeConsumer Received message: {} is not json", message);
			return;
		}

		BusinessOrderStatusChangeMsg statusChangeMsg = JSONUtil.toBean(message, BusinessOrderStatusChangeMsg.class);
		isNull(statusChangeMsg, ErrorMessage.ARGUMENT_NOT_VALID);
		log.info("PersonalMintBusinessOrderPayStatusChangeConsumer statusChangeMsg: {}", message);
		
		BusinessOrderResponse businessOrderDto = iInnerService.businessOrderInfoWithId(statusChangeMsg.getBusinessOrderId());
		if (Objects.isNull(businessOrderDto)) {
			log.error("PersonalMintBusinessOrderPayStatusChangeConsumer can not find businessOrder Received message: {}", message);
			return;
		}
		tblAssetAuditService.setAssetAuditStatus(businessOrderDto.getAppUserId(), Long.valueOf(businessOrderDto.getGoodsId()), 1);
	}
}
